<template>
  <div class="profile-container">
    <div class="header">
      <div class="header-content">
        <div class="back-btn" @click="goBack">
          <el-icon><ArrowLeft /></el-icon>
          <span>返回</span>
        </div>
        <h1 class="title">个人信息</h1>
        <div></div>
      </div>
    </div>

    <div class="main-content">
      <el-card shadow="hover" class="profile-card">
        <div class="profile-header">
          <div class="avatar-container">
            <el-avatar :size="100" :src="userInfo?.avatar || defaultAvatar">
              {{ userInfo?.nickname?.charAt(0) || 'U' }}
            </el-avatar>
            <div class="avatar-overlay" @click="triggerUpload">
              <el-icon :size="24"><Camera /></el-icon>
              <span>更换头像</span>
            </div>
            <input 
              ref="fileInput" 
              type="file" 
              accept="image/*" 
              style="display: none" 
              @change="handleFileChange"
            />
          </div>
          <div class="profile-info">
            <h2>{{ userInfo?.nickname || userInfo?.username }}</h2>
            <p class="user-id">ID: {{ userInfo?.id }}</p>
            <el-tag :type="userInfo?.status === 1 ? 'success' : 'danger'" size="small">
              {{ userInfo?.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </div>
        </div>

        <el-divider />

        <div class="profile-details">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="用户名">
              <div class="detail-item">
                <el-icon><User /></el-icon>
                <span>{{ userInfo?.username }}</span>
              </div>
            </el-descriptions-item>

            <el-descriptions-item label="昵称">
              <div class="detail-item">
                <el-icon><Avatar /></el-icon>
                <span>{{ userInfo?.nickname || '未设置' }}</span>
              </div>
            </el-descriptions-item>

            <el-descriptions-item label="邮箱">
              <div class="detail-item">
                <el-icon><Message /></el-icon>
                <span>{{ userInfo?.email || '未设置' }}</span>
              </div>
            </el-descriptions-item>

            <el-descriptions-item label="手机号">
              <div class="detail-item">
                <el-icon><Phone /></el-icon>
                <span>{{ userInfo?.phone || '未设置' }}</span>
              </div>
            </el-descriptions-item>

            <el-descriptions-item label="账号状态">
              <div class="detail-item">
                <el-icon><CircleCheck /></el-icon>
                <el-tag :type="userInfo?.status === 1 ? 'success' : 'danger'">
                  {{ userInfo?.status === 1 ? '正常' : '禁用' }}
                </el-tag>
              </div>
            </el-descriptions-item>

            <el-descriptions-item label="注册时间">
              <div class="detail-item">
                <el-icon><Clock /></el-icon>
                <span>{{ formatDate(userInfo?.createTime) }}</span>
              </div>
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <div class="profile-actions">
          <el-button type="primary" @click="goHome">
            <el-icon><HomeFilled /></el-icon>
            返回首页
          </el-button>
          <el-button type="danger" @click="handleLogout">
            <el-icon><SwitchButton /></el-icon>
            退出登录
          </el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { 
  ArrowLeft, 
  User, 
  Avatar, 
  Message, 
  Phone, 
  CircleCheck, 
  Clock, 
  HomeFilled, 
  SwitchButton,
  Camera
} from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { uploadAvatar } from '@/api/user'

const router = useRouter()
const userStore = useUserStore()
const fileInput = ref(null)
const uploading = ref(false)

const userInfo = computed(() => userStore.userInfo)
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '未知'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 返回首页
const goHome = () => {
  router.push('/home')
}

// 触发文件选择
const triggerUpload = () => {
  fileInput.value.click()
}

// 处理文件选择
const handleFileChange = async (event) => {
  const file = event.target.files[0]
  if (!file) return
  
  // 验证文件类型
  if (!file.type.startsWith('image/')) {
    ElMessage.error('请选择图片文件')
    return
  }
  
  // 验证文件大小（最大5MB）
  if (file.size > 5 * 1024 * 1024) {
    ElMessage.error('图片大小不能超过5MB')
    return
  }
  
  try {
    uploading.value = true
    const response = await uploadAvatar(userInfo.value.id, file)
    
    if (response.code === 200) {
      ElMessage.success('头像上传成功')
      // 更新用户信息
      await userStore.fetchUserFullInfo(userInfo.value.id)
    } else {
      ElMessage.error(response.message || '头像上传失败')
    }
  } catch (error) {
    console.error('上传头像失败:', error)
    ElMessage.error('头像上传失败')
  } finally {
    uploading.value = false
    // 清空文件选择
    event.target.value = ''
  }
}

// 退出登录
const handleLogout = () => {
  ElMessageBox.confirm('确定要退出登录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    userStore.logout()
  }).catch(() => {
    // 取消操作
  })
}
</script>

<style scoped>
.profile-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  transition: background 0.3s;
}

.dark .profile-container {
  background: linear-gradient(135deg, #1e3a8a 0%, #581c87 100%);
}

.header {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.header-content {
  max-width: 800px;
  margin: 0 auto;
  padding: 0 20px;
  height: 64px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.back-btn {
  display: flex;
  align-items: center;
  gap: 5px;
  cursor: pointer;
  color: #666;
  font-size: 14px;
  transition: color 0.3s;
}

.back-btn:hover {
  color: #667eea;
}

.title {
  font-size: 20px;
  color: #333;
  font-weight: 500;
}

.main-content {
  max-width: 800px;
  margin: 0 auto;
  padding: 40px 20px;
}

.profile-card {
  padding: 20px;
}

.profile-header {
  display: flex;
  align-items: center;
  gap: 30px;
  padding: 20px;
}

.avatar-container {
  position: relative;
  cursor: pointer;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 5px;
  opacity: 0;
  transition: opacity 0.3s;
  color: white;
  font-size: 12px;
}

.avatar-container:hover .avatar-overlay {
  opacity: 1;
}

.profile-info {
  flex: 1;
}

.profile-info h2 {
  font-size: 24px;
  color: #333;
  margin-bottom: 8px;
}

.user-id {
  font-size: 14px;
  color: #999;
  margin-bottom: 10px;
}

.profile-details {
  margin: 20px 0;
}

.detail-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #333;
}

.profile-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}

:deep(.el-descriptions__label) {
  width: 120px;
  font-weight: 500;
}

:deep(.el-descriptions__content) {
  font-size: 14px;
}
</style>